package com.ifonly.render.renders;

import com.google.common.base.Strings;
import com.ifonly.render.Render;

import java.io.IOException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 10:37
 * @since JDK 1.6
 */
public class RedirectRender extends Render {

    public RedirectRender(String view) {
        super(view, null);
    }

    @Override
    public void render() {
        try {
            String ctx = request.getContextPath();
            if (Strings.isNullOrEmpty(ctx)) {
                ctx = "/";
            }

            String path;

            if (view.startsWith("/")) {
                if (ctx.equals("/")) {
                    path = view;
                } else {
                    path = ctx + view;
                }
            } else {
                if (Strings.isNullOrEmpty(viewDir)) {
                    path = ctx + "/" + view;
                } else if ("/".equals(viewDir)) {
                    path = ctx + "/" + view;
                } else {
                    if (!viewDir.startsWith("/")) {
                        path = ctx + "/" + viewDir;
                    } else {
                        path = ctx + viewDir;
                    }
                    if (!viewDir.endsWith("/")) {
                        path = path + "/";
                    }
                    path = path + view;
                }
            }
            response.sendRedirect(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
